package fpt.edu.vn.util;



import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.imageio.ImageIO;

import org.imgscalr.Scalr;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class ImageUtil {

    static int min = 400;
    static int max = 800;
    public String leechIMG(File string) {
        String result = "http://i.imgur.com/41SYW.png";
        OutputStreamWriter wr;
        try {
            BufferedImage img = ImageIO.read(string);
            if (img == null) {
                img = ImageIO.read(new URL(result));
            }
            BufferedImage scaledImage = Scalr.resize(img, Scalr.Mode.FIT_TO_WIDTH, 114);

            // Creates Byte Array from picture
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(scaledImage, "png", baos);
            URL imgurURL = null;
            try {
                imgurURL = new URL("http://api.imgur.com/2/upload");
                
            } catch (MalformedURLException ex) {
                //Logger.getLogger(Leecher.class.getName()).log(Level.SEVERE, null, ex);
            }
            //encodes picture with Base64 and inserts api key  976225bbb15de1ec6cddaa4a8f7c6dab   99efc6626ed232681055b2621e5487b4
            String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encode(baos.toByteArray()), "UTF-8");
            data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("976225bbb15de1ec6cddaa4a8f7c6dab", "UTF-8");
            // opens connection and sends data
            URLConnection conn = imgurURL.openConnection();
            conn.setDoOutput(true);
            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            wr.close();
            // Get the response
            InputStream is;
            if (((HttpURLConnection) conn).getResponseCode() == 400) {
                is = ((HttpURLConnection) conn).getErrorStream();
            } else {
                is = conn.getInputStream();
            }
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String xml = "";
            try  {
            	
                String line;
                while ((line = rd.readLine()) != null) {
                    xml += line;
                }
            }catch(Exception ex){
            	
            }
            Document doc = Jsoup.parse(xml);
            result = doc.getElementsByTag("original").first().html();
            
        } catch (IOException ex) {
            //Logger.getLogger(Leecher.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
//    public void resize(File originalFile, File resizedFile, float quality) throws IOException {
//        int newWidth = 640;
//        if (quality < 0 || quality > 1) {
//            throw new IllegalArgumentException("Quality has to be between 0 and 1");
//        }
//
//        ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
//        Image i = ii.getImage();
//        Image resizedImage = null;
//
//        int iWidth = i.getWidth(null);
//        int iHeight = i.getHeight(null);
//        if (iWidth < min) {
//            newWidth = min;
//        }
//        if (iWidth > max) {
//            newWidth = max;
//        }
//
//        if (iWidth > iHeight) {
//            resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
//        } else {
//            resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
//        }
//
//        // This code ensures that all the pixels in the image are loaded.
//        Image temp = new ImageIcon(resizedImage).getImage();
//
//        // Create the buffered image.
//        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),BufferedImage.TYPE_INT_RGB);
//
//        // Copy image to buffered image.
//        Graphics g = bufferedImage.createGraphics();
//
//        // Clear background and paint the image.
//        g.setColor(Color.white);
//        g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
//        g.drawImage(temp, 0, 0, null);
//        g.dispose();
//
//        // Soften.
//        float softenFactor = 0.05f;
//        float[] softenArray = {0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0};
//        Kernel kernel = new Kernel(3, 3, softenArray);
//        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
//        bufferedImage = cOp.filter(bufferedImage, null);
//
//        // Write the jpeg to a file.
//        FileOutputStream out = new FileOutputStream(resizedFile);
//
//        ImageIO.write(bufferedImage, "jpg", resizedFile);
//        out.close();
//    }
}